// pages/main/index.js

import QR from '../../utils/qrcode.js'
import base64 from '../../utils/base64'
const baseUrl = 'https://sichuangyi.demopp.in/signup?id='

Page({
  data: {
    loading: true
  },
  onLoad: function (options) {
    if (!options.id || !options.name) {
      return
    }
    this.setData({
      ...options,
      qrUrl: baseUrl + options.id
    })
    let drawName = `${options.name}签到码`

    let size = this.setCanvasSize()
    QR.qrApi.draw(this.data.qrUrl, "mycanvas", size.w, size.h, drawName)
  },
  onReady: function () {
    let drawName = `${this.data.name}签到码`
    let size = this.setCanvasSize()
    QR.qrApi.draw(this.data.qrUrl, "mycanvas", size.w, size.h, drawName)
    this.setData({
      loading: false
    })
  },
  //适配不同屏幕大小的canvas
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync()
      var scale = 750 / 686;//不同屏幕下canvas的适配比例；设计稿是750宽
      var width = res.windowWidth / scale
      var height = width//canvas画布为正方形
      size.w = width
      size.h = height
    } catch (e) {
      // Do something when catch error
      throw new Error(e)
    }
    return size
  },
  //点击图片进行预览，长按保存分享图片
  saveImage: function (e) {
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 3000
            })
          },
          fail: function (res) {
            wx.showToast({
              title: '保存失败',
              icon: 'error',
              duration: 300
            })
          }
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '保存失败',
          icon: 'error',
          duration: 300
        })
      }
    })
  }
})
